package com.inspectortime.webapp.util;

import java.beans.PropertyEditorSupport;
import java.text.DateFormat;
import java.text.ParseException;
import java.util.Calendar;

import org.apache.commons.lang.StringUtils;

/**
 * Custom editor for binding Calendar class
 * 
 * @author bones
 *
 */
public class CustomCalendarEditor extends  PropertyEditorSupport {
	
	private DateFormat dateFormat;
	private boolean allowEmpty;
	
	public CustomCalendarEditor(DateFormat dateFormat, boolean allowEmpty) {
		this.dateFormat = dateFormat;
		this.allowEmpty = allowEmpty;
	}
	
	public String getAsText() {
		  Calendar value = (Calendar) getValue();
		  return (value != null ? this.dateFormat.format(value.getTime()) : "");
	}
	
	public void setAsText(String text) throws IllegalArgumentException {
	    if (this.allowEmpty && StringUtils.isBlank(text)) {
	      setValue(null);
	    } else {
	      try {
	        Calendar cal = Calendar.getInstance();
	        cal.setTime(this.dateFormat.parse(text));
	        correctTwoDigitYear(cal);
	        setValue(cal);
	    } catch (ParseException ex) {
	      throw new IllegalArgumentException();
	    }
	  }
	}

	private void correctTwoDigitYear(Calendar cal) {
		int year = cal.get(Calendar.YEAR); 
		if ((year - 2000) < 0){
			cal.set(Calendar.YEAR, year + 2000);
		}
	}
	
}
